import sys
sys.path.append("./")

from common.emqx.emqx_client import EMQXClient
from sensor_reader import SensorReader
import json
import time
import uuid

TOPIC_ORANGEPI_RECIVE_TEMP = "orangepi_receive_temp"
TOPIC_ORANGEPI_SEND_TEMP = "orangepi_send_temp"

# 初始化传感器读取器
sensor_reader = SensorReader()

# 自定义消息处理回调
def handle_message(client, userdata, msg):
    try:
        data = json.loads(msg.payload)
        print(f"[应用] 收到结构化数据: {data}")
        
        if data.get('requestType') == 'send':
            print("[应用] 检测到发送指令，准备发送传感器数据...")
            
            # 读取传感器数据
            sensor_data = sensor_reader.read_all()
            
            # 构建响应消息
            # response = 
            # sender.publish(
            #         topic=TOPIC_ORANGEPI_TEMP,
            #         payload={"requestId":data.get('requestId'),"requestType":"receive","type": "temp", "value": "47"},
            #         qos=1
            #     )
            # 发送响应
            with sender:
                sender.publish(
                    topic=TOPIC_ORANGEPI_SEND_TEMP,
                    payload={
                        "requestId": data.get('requestId'),
                        "requestType": "receive",
                        "type": "sensor_data",
                        "value": sensor_data
                    },
                    qos=1
                )
            print("[应用] 传感器数据已发送")
            
    except json.JSONDecodeError as e:
        print(f"[应用] JSON解析失败: {e}，原始内容: {msg.payload.decode()}")
    except Exception as e:
        print(f"[应用] 未知错误: {e}")

# 初始化EMQX客户端
receiver = EMQXClient(
    client_id=f"orangepi_mqreceive_{uuid.uuid4()}",
    broker="192.168.1.42",
    port=8083
)

sender = EMQXClient(
    client_id=f"orangepi_mqsender1_{uuid.uuid4()}",
    broker="192.168.1.42",
    port=8083
)

# 注册自定义回调
receiver.register_message_callback(handle_message)

# 主循环
with receiver:
    # 避免发出去的消息被自己接收
    receiver.subscribe(TOPIC_ORANGEPI_RECIVE_TEMP, qos=1)
    while True:
        time.sleep(1)